package com.qxsx.midi.activity.me;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.adapter.MyAdapter;
import com.qxsx.midi.db.MyFileDBTool;
import com.qxsx.midi.model.MyFile;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.Tools;
import com.qxsx.midi.utils.Utils;
import com.qxsx.midi.utils.callBackJsonArray;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.List;

/**
 * Created by Zrj on 2015/9/15.
 */
public class AppVideoAddActivity extends Activity implements View.OnClickListener {

    private RelativeLayout rl_sousuo;
    private ListView lv_files; // 显示满足条件的文件的名称
    private BaseAdapter myAdapter; // lv_files的适配器
    private List<MyFile> data; // lv_file的数据源
    private AlertDialog dialog_deleteFile; // 长按ListView的Item所弹出的删除文件对话框
    private static Handler handler;
    private final static int WHAT_UPDATETEXT = 1; // 获取到一条匹配的数据时更新数据
    private final static int WHAT_ITEMCLICK = 2; // ListView的Item点击后需要更新数据,用来改变item选中时的背景颜色
    private final static int WHAT_SEARCHFINISHED = 3; // 搜索结束时发消息更新数据
    private final static int WHAT_DELETEFILE = 5;// 长按删除后用来修改当前数据的总数
    private static MyFileDBTool myFileDBTool; // 执行对数据库的相关操作
    private File root; // 所要搜索文件的根目录
    private String file_path = "";// 所选择文件的路径
    public static int pos; // 用来使选中的item保持常亮
    private SharedPreferences movie_pos; // 有关影片的首选项信息


    private int scroll_position; // 判断滚动的位置
    private Thread searchThread; // 搜索功能的线程


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_apply_videoadd);
        Tools.checkPathFile(Utils.ROOT_files); // 创建wanzheng的路径
        getSDCardPathEx();


        lv_files = (ListView) findViewById(R.id.lv_files);

        rl_sousuo = (RelativeLayout) findViewById(R.id.rl_sousuo);
        rl_sousuo.setOnClickListener(this);
        myFileDBTool = new MyFileDBTool(this);
        data = myFileDBTool.getAll(); // 数据源，从数据库中读取而来
        myAdapter = new MyAdapter(this, data);
        lv_files.setAdapter(myAdapter); // ListView设置适配器
        // ListView 单击响应事件
        lv_files.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                pos = position;

                file_path = data.get(position).getFilePath();
                //  Toast.makeText(AppVideoAddActivity.this, file_path, Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessage(WHAT_ITEMCLICK);
                Intent intent = new Intent();
                intent.putExtra("file_path",file_path);
                setResult(200, intent);
//                Apply();
                finish();

            }
        });
        // ListView 滚动监听事件
        lv_files.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    scroll_position = lv_files.getFirstVisiblePosition();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
            }
        });
        // 用来修改控件的外观
        handler = new Handler() {
            // 重新定义handlerMessage() 回调方法 ==> 收到消息之后执行自己的逻辑
            public void handleMessage(Message msg) {

                switch (msg.what) {
                    case WHAT_UPDATETEXT:
                        MyFileDBTool myFileDBTool1 = null; // 执行对数据库的相关操作
                        myFileDBTool1 = new MyFileDBTool(AppVideoAddActivity.this);
                        data = myFileDBTool1.getAll();
                        myAdapter = new MyAdapter(AppVideoAddActivity.this, data); // 重新new
                        lv_files.setAdapter(myAdapter); // 重新设置适配器
                        lv_files.setSelectionFromTop(scroll_position, -80);
                        break;

                    case WHAT_ITEMCLICK:
                        MyFileDBTool myFileDBTool2 = null; // 执行对数据库的相关操作
                        myFileDBTool2 = new MyFileDBTool(AppVideoAddActivity.this);
                        data = myFileDBTool2.getAll();
                        myAdapter = new MyAdapter(AppVideoAddActivity.this, data); // 重新new
                        lv_files.setAdapter(myAdapter); // 重新设置适配器
                        lv_files.setSelectionFromTop(scroll_position, -80);
                        break;
                    case WHAT_SEARCHFINISHED:

                        MyFileDBTool myFileDBTool3 = null; // 执行对数据库的相关操作
                        myFileDBTool3 = new MyFileDBTool(AppVideoAddActivity.this);
                        data = myFileDBTool3.getAll();
                        myAdapter = new MyAdapter(AppVideoAddActivity.this, data); // 重新new
                        lv_files.setAdapter(myAdapter); // 重新设置适配器
                        lv_files.setSelectionFromTop(scroll_position, -80);
                        rl_sousuo.setVisibility(View.VISIBLE);
                        break;


                    case WHAT_DELETEFILE:
                        MyFileDBTool myFileDBTool5 = null; // 执行对数据库的相关操作
                        myFileDBTool5 = new MyFileDBTool(AppVideoAddActivity.this);
                        data = myFileDBTool5.getAll();
                        break;


                }
            }
        };

    }

    /**
     * 上传视频
     */

    private void Apply(){
        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            File file = new File(file_path);
            InputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            object.put("content",buffer + "");
            array.put(object);

        } catch (Exception e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("8041", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                Log.w("code", code + "");
                Log.w("message", message + "");
                Log.w("array", array + "");
            }
        });


    }





    /**
     * 外置SD卡
     */

    public String getSDCardPathEx() {
        String mount = new String();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                if (line.contains("secure"))
                    continue;
                if (line.contains("asec"))
                    continue;

                else if (line.contains("fuse")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        mount = mount.concat(columns[1] + "\n");
                        Tools.writefile(Utils.ROOT_writeText, mount, false);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return mount;
    }

    /**
     * 处理搜索功能的线程
     *
     * @author zhgyi
     */
    public class DoingSearch implements Runnable {
        @Override
        public void run() {
            File file = new File(Utils.ROOT_writeText);
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String tempString = "";
                // 一次读入一行，直到读入null为文件结束
                while ((tempString = reader.readLine()) != null) {
                    // 显示行号
                    if (tempString.contains("mnt")) {
                        continue;
                    }
                    if (tempString.contains("legacy")) {
                        continue;
                    } else {
                        try {
                            root = new File(tempString);
                            if (root.exists()) {
                                showAllFiles(root);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
                reader.close();
                handler.sendEmptyMessage(WHAT_SEARCHFINISHED);
            } catch (IOException e) {
                String[] a = {Utils.ROOT, "/storage/extSdCard", "/storage/sdcard1"};

                try {
                    for (int i = 0; i <= 1; i++) {
                        root = new File(a[i]);
                        Log.w("ssss", root + "");
                        if (root.exists()) {
                            showAllFiles(root);
                        }
                    }
                    handler.sendEmptyMessage(WHAT_SEARCHFINISHED);

                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                    }
                }
            }
        }
    }

    /**
     * 给定路径并将所选路径下的符合格式的文件保存到数据库当中
     *
     * @param fileAbsolutePath String类型的文件路径
     * @return void
     */
    public void getTestFileName(String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);

        if (!file.isDirectory()) {
            String tempName = file.getName();
            file.length();
//            || tempName.trim().toLowerCase().endsWith(".mkv")
//                    || tempName.trim().toLowerCase().endsWith(".flv")
//                    || tempName.trim().toLowerCase().endsWith(".avi")
//                    || tempName.trim().toLowerCase().endsWith(".3gp")
//                    || tempName.trim().toLowerCase().endsWith(".wmv")
//                    || tempName.trim().toLowerCase().endsWith(".rmvb")
//                    || tempName.trim().toLowerCase().endsWith(".mov")
            // 判断是否满足给定格式的文件结尾
            if (tempName.trim().toLowerCase().endsWith(".mp4")
                    ) {

                byte[] imagesize = null; // 将缩略图转换为字节
                int isHaveThumbnail = 0;
                try {
                    imagesize = Tools.bitmapToBytes(Tools.getVideoThumbnail(
                            file.getAbsolutePath(), 100, 100,
                            MediaStore.Images.Thumbnails.MINI_KIND));
                    isHaveThumbnail = 1;
                } catch (Exception e) {
                    Bitmap newb = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565);
                    imagesize = Tools.bitmapToBytes(newb);
                    isHaveThumbnail = 0;
                }
                MyFile myfile = new MyFile(tempName, Tools.getFormatSize(file
                        .length()),
                        new Timestamp(file.lastModified()).toString(),
                        file.getAbsolutePath(), imagesize, isHaveThumbnail);
                // if (!myFileDBTool.getOne(tempName)) {
                myFileDBTool.insertOne(myfile);
                handler.sendEmptyMessage(WHAT_UPDATETEXT);
                // }
            }
        }
    }

    /**
     * 扫描对话框 在扫描按钮被单击后执行此方法<br/>
     * 重写了Dialog 内部控件重新布局
     */
    private void showDialog() {
        myFileDBTool.deleteAll();
        searchThread = new Thread(new DoingSearch());
        searchThread.start();
    }

    /**
     * 遍历接收一个文件路径，然后把文件子目录中的所有文件遍历并输出来
     *
     * @param dir File类型的文件
     * @return void
     */
    final void showAllFiles(final File dir) throws Exception {
        File[] fs = dir.listFiles();
        for (int i = 0; i < fs.length; i++) {
//            if (!fs[i].getAbsolutePath().contains(
//                    new String(Utils.ROOT + "/Android"))) {
            if (fs[i].isDirectory()) {
                try {
                    showAllFiles(fs[i]); // 如果是一个文件夹返回继续遍历
                } catch (Exception e) {
                }
            } else {
                getTestFileName(fs[i].getAbsolutePath());
            }
//            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_sousuo:
                rl_sousuo.setVisibility(View.GONE);
                showDialog();

                break;
            default:
                break;
        }

    }
}
